package com.repair.dao.Module.impl;



import java.util.ArrayList;

import java.util.List;

import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;



import com.repair.dao.Module.IModuleDao;
import com.repair.domain.Module;
import com.repair.factory.HibernateSessionFactory;
;

public class ModuleDao implements IModuleDao {

	@Override
	public void saveModule(Module obj) {
		Session session = HibernateSessionFactory.getSession();

		try {
			Transaction tx = session.beginTransaction();
			if (session != null) {
				session.saveOrUpdate(obj);
				tx.commit();
				session.flush();
				session.clear();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (session != null) {
				session.flush();
				session.clear();
			}
		}
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Module> getAllModule() {
		List<Module> list = new ArrayList<Module>();
		Session session = HibernateSessionFactory.getSession();
		try {
			if (session != null) {
				String sql = "select * from MODULE";
				SQLQuery query = session.createSQLQuery(sql);
				list = query.addEntity(Module.class).list();
			}
		} catch (Exception e) {

		} finally {
			if (session != null) {
				session.flush();
				session.clear();
			}
		}
		return list;

	}

	@Override
	public void deleteModule(String id) {
		Session session = HibernateSessionFactory.getSession();
		try {
			Transaction tx = session.beginTransaction();
			if (session != null) {
				String sql = "delete from MODULE where MODULE_ID in ("+id+")";
				SQLQuery query = session.createSQLQuery(sql);
				query.executeUpdate();
				tx.commit();
			}
		} catch (Exception e) {

		} finally {
			if (session != null) {
				session.flush();
				session.clear();
			}
		}

	}
	
	public List<Module> serchmodule(String key) {
		Module m=null;
		List<Module> module = new ArrayList<Module>();
		Session session = HibernateSessionFactory.getSession();
		try {
			if (session != null) {
				String sql = "select * from MODULE where MODULE_ID like '%"+key+"%' or MODULE_NAME like '%"+key+"%' or MODULE_VIEW like '%"+key+"%'";
				SQLQuery query = session.createSQLQuery(sql);
				module = query.addEntity(Module.class).list();
				
			}
		} catch (Exception e) {

		} finally {
			if (session != null) {
				session.flush();
				session.clear();
			}
		}
		return module;
		
	}
	
}
